package com.hmall.item.web;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 分页
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> pagingQuery(Integer page,Integer size){
        Page<Item> result = itemService.page(new Page<>(page, size));
        return new PageDTO<>(result.getTotal(),result.getRecords());
    }


    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item queryById(@PathVariable Long id){
        Item item = itemService.getById(id);
        return item;
    }


    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void newGoods(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2);
        itemService.save(item);
    }


    /**
     * 修改商品状态
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void modifyCommodityStatus(@PathVariable Long id,@PathVariable Integer status){
        Item item = itemService.getById(id);
        item.setUpdateTime(new Date());
        item.setStatus(status);
        itemService.updateById(item);

        // 根据上下架判断RoutingKey
        String routingKey = status == 1 ? "item.up" : "item.down";
        // 发送消息
        rabbitTemplate.convertAndSend("item.topic", routingKey, id);
    }


    /**
     * 修改商品
     * @param item
     */
    @PutMapping
    public void modifyMerchandise(@RequestBody Item item){
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }


    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteGoods(@PathVariable Long id){
        itemService.removeById(id);
    }













}
